<template>
  <div class="page-bg">
    <listTable
      ref="tableRef"
      v-model="tableData"
      :isCheck="false"
      @getList="getList"
      :pageSizes="[100]"
    >
      <template #action>
        <el-button @click="showFun()" type="primary"
          >新增{{ typeName }}分类</el-button
        >
      </template>
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="id" label="ID" width="100" align="center" />
      <el-table-column label="图片" width="100" align="center" v-if="showImg">
        <template #default="scope">
          <el-image
            style="width: 38px; height: 38px"
            :preview-src-list="[scope.row.imgUrl]"
            :src="scope.row.imgUrl"
            fit="contain"
            preview-teleported
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        width="100"
        label="状态"
        :filters="[
          { text: '显示', value: '1' },
          { text: '隐藏', value: '0' },
        ]"
        :filter-method="filterTag"
        filter-placement="bottom-end"
      >
        <template #default="scope">
          <el-tag v-if="scope.row.a_show == '1'" type="success">显示</el-tag>
          <el-tag v-else type="info">隐藏</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="sort"
        label="排序"
        width="100"
        align="center"
        sortable="custom"
      />
      <el-table-column
        prop="up_time"
        label="更新时间"
        width="180"
        align="center"
      />
      <el-table-column
        prop="create_time"
        label="创建时间"
        width="180"
        align="center"
      />
      <el-table-column fixed="right" label="操作栏" width="140" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="showFun(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm title="确定删除？" @confirm="delFn(scope.row)">
            <template #reference>
              <el-button link type="primary" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </listTable>

    <!-- 表单弹窗 -->
    <el-dialog
      v-model="layerForm.show"
      :title="layerForm.form.id ? '编辑分类' : '新增分类'"
      width="640px"
    >
      <el-form label-position="top" label-width="100px">
        <div class="flex form">
          <div class="b1">
            <el-form-item label="图片：" v-if="showImg">
              <formImg
                v-model="layerForm.form.img"
                width="192"
                height="192"
                @pickImg="pickImg('img', $event)"
              />
            </el-form-item>
          </div>
          <div class="b2">
            <el-form-item label="所属上级分类：">
              <el-select v-model="layerForm.form.pid" placeholder="Select">
                <el-option label="无" :value="0" />
                <el-option
                  v-for="v in tableData.lists"
                  :key="v.id"
                  :label="v.name"
                  :value="v.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="分类名称：">
              <el-input
                v-model.trim="layerForm.form.name"
                placeholder="请输入分类名称"
              ></el-input>
            </el-form-item>
            <div class="flex">
              <el-form-item label="排序：" style="width: 215px">
                <el-input
                  v-model.trim="layerForm.form.sort"
                  type="number"
                  maxlength="10"
                  placeholder="数字越大排名越靠前，0最小"
                ></el-input>
              </el-form-item>
              <el-form-item label="分类状态：" style="margin-left: 30px">
                <el-radio v-model="layerForm.form.a_show" label="1">
                  显示
                </el-radio>
                <el-radio v-model="layerForm.form.a_show" label="0">
                  隐藏
                </el-radio>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div class="lfex">
        <el-button size="large" @click="layerForm.show = false">取消</el-button>
        <el-button size="large" type="primary" @click="subForm">确定</el-button>
      </div>
    </el-dialog>
    <layerImg v-model="imgOption.show" @getImg="getImg" space="other" />
  </div>
</template>

<script lang="ts" setup>
import { listTable, typeColumn } from "@/components/listPage/index";
import config from "@/common/config";
import { ElMessage } from "element-plus";
import {
  tableDataType,
  typeItem,
  typeItemTypeName,
  tableDataQuery,
} from "@/common/interface";
import { post } from "@/common/http";
import dayjs from "dayjs";
import { layerImg, formImg, useImgHook } from "@/components/formImg";
import { build_tree } from "@/common/tool";
const { imgOption, pickImg } = useImgHook();

interface IProps {
  type: typeItemTypeName;
  typeName?: string;
  showImg?: boolean; //是否显示图片模块
}
const props = withDefaults(defineProps<IProps>(), {
  type: typeItemTypeName.goods,
  showImg: () => false,
});

const tableRef = ref();

//表格组件数据
const tableData = reactive<tableDataType<typeItem>>(new tableDataType());

//获取列表
function getList(data: tableDataQuery): void {
  post("api/Type/list_data_a", {
    page: data.page,
    limit: data.limit,
    type: props.type,
    sortField: data.sortField, //需要排序的字段
    sort: data.sort, //desc asc
  }).then((res) => {
    tableData.lists = build_tree(
      res.data.map((v: typeItem) => {
        return {
          ...v,
          imgUrl: config.serverImg + (v.img ? v.img : "default.jpg"),
          up_time: dayjs(Number(v.up_time) * 1000).format(
            "YYYY-MM-DD HH:mm:ss"
          ),
          create_time: dayjs(Number(v.create_time) * 1000).format(
            "YYYY-MM-DD HH:mm:ss"
          ),
        };
      }),
      0
    );
    tableData.total = res.total ?? 0;
    tableData.loading = false;
  });
}

//删除 / 批量删除
function delFn(item: typeItem) {
  if (item.children.length) {
    return ElMessage.error("请先删除当前分类下的分类");
  } else {
    post("api/Type/type_del_data", { id: item.id, name: item.name }).then(() =>
      tableRef.value.reload()
    );
  }
}

//筛选当前页数据的 状态
const filterTag = (value: string, row: typeItem) => {
  return row.a_show === value;
};

//编辑
const layerForm = reactive({
  show: false,
  form: new typeItem(props.type),
});
function showFun(data?: typeItem) {
  if (data) {
    layerForm.form = JSON.parse(JSON.stringify(toRaw(data)));
  } else {
    layerForm.form = new typeItem(props.type);
  }
  layerForm.show = true;
}

function subForm() {
  let data = toRaw(layerForm.form);
  if (!data.name) return ElMessage.error("请输入分类名称");
  post("api/Type/editType", data).then((res) => {
    tableRef.value.reload();
    ElMessage.success(res.msg);
    layerForm.show = false;
  });
}

//获取弹窗选择的图片
function getImg(data: any) {
  //单图上传
  if (imgOption.option.name === "img") {
    layerForm.form.img = data.imgUrl;
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  padding: 0 10px 10px;
}
.form {
  align-items: flex-start;
  .b2 {
    flex: 1;
    margin-left: 20px;
  }
}
</style>
